<?php

abstract class a_base_model_datamapper extends DataMapper implements i_base_model {

    protected $dynamic_props;

    function __construct($id = NULL) {
        parent::__construct($id);
        $this->load_dynamic_properties();
    }

    public function ci() {
        return get_instance();
    }

    public function db() {
        return $this->db;
    }

    public function count_dynamic_props() {
        return count($this->dynamic_props);
    }

    public function list_dynamic_props() {
        return array_keys($this->dynamic_props);
    }

    public function __get($key) {
        if (starts_with($key, a_dynamic_prop::PREFIX)) {
            if (isset($this->dynamic_props[$key])) {
                $obj = $this->dynamic_props[$key]->obj;
                if ($this->dynamic_props[$key]->data === NULL) {
                    $this->dynamic_props[$key]->data = $obj->run($this);
                } else {
                    if (!$obj->run_once()) {
                        $this->dynamic_props[$key]->data = $obj->run($this);
                    }
                }
                return $this->dynamic_props[$key]->data;
            }
        } else {
            return parent::__get($key);
        }
    }

    public function load_dynamic_properties() {
        //@TO_DO : create a helper functoin that can a the module name from filename
        $class_name_parts = explode("_m_",get_class($this));
        $module = @$class_name_parts[1];

        $path = APPPATH . a_dynamic_prop::PROPERTY_FOLDER_NAME . "/" . $module . "/" . get_class($this);
        $files = get_filenames($path);

        if ($files && count($files) > 0) {
            foreach ($files as $file) {
                if (is_file($path . "/" . $file)) {
                    //@TO_DO : user quick_include()
                    include_once $path . "/" . $file;
                    $prop_class = current(explode(".", $file));
                    $obj = new $prop_class($this);
                    $this->dynamic_props[$obj->get_property_name()]->obj = $obj;
                    $this->dynamic_props[$obj->get_property_name()]->data = NULL;
                }
            }
        }
    }

    public function load_dynamic_attributes() {
//        $path = APPPATH . a_dynamic_attr::ATTRIBUTE_FOLDER_NAME . "/" . $this->ci()->current_module . "/" . get_class($this);
//        $files = get_filenames($path);
//        if (count($files) > 0) {
//            foreach ($files as $file) {
//                if (is_file($path . "/" . $file)) {
//                    include_once $path . "/" . $file;
//                    $prop_class = current(explode(".", $file));
//                    $obj = new $prop_class();
//                    $obj->add();
//                }
//            }
//        }
        return NULL;
    }

    public function convert_to_simple_data() {
        return new datamapper_model2data_converter($this);
    }

}

?>